define(['js/init','js/util/notify','js/util/toast'],function(init,notify,toast) {
	
	'use strict';

	//socket连接状态
	var socketStatus = false;

	var webSocket = null; 

	function initSocket(userid) {  
      
		      
		 
	  
		if (!window.WebSocket) {  
			console("您的浏览器不支持websocket！");  
			return false;  
		}  
  
		var target = init.ws + userid;    
				
			if ('WebSocket' in window) {    
				webSocket = new WebSocket(target);    
			} else if ('MozWebSocket' in window) {    
				webSocket = new MozWebSocket(target);    
			} else {    
				alert('WebSocket is not supported by this browser.');    
				return;    
			}

		//根据登录用户修改websocket路径
        init.setWsPath(userid);
      
		// 收到服务端消息  
		webSocket.onmessage = function (msg) {  
			
			var mjson = JSON.parse(msg);
			
			//显示图标badges
			if(mjson && mjson.bizcode === 'notification'){
				var badges =mjson.data;
				cordova.plugins.notification.badge.get(function (badge) {
					badges = badge;
				});

				if(badges > 0 ){
					cordova.plugins.notification.badge.set(badges);
				}
			}
			console.log(event);  
			notify.notify();
			// 关闭连接  
			//webSocket.onclose();  
			console.log(msg);  
		};  
	  
		// 异常  
		webSocket.onerror = function (event) {  
			console.log(event);  
		};  
	  
		// 建立连接  
		webSocket.onopen = function (event) { 
			socketStatus  = true;
			notify.notify();
			console.log(event);  
		};  
	  
		// 断线  
		webSocket.onclose = function () {  
			socketStatus = false;
			console.log("websocket断开连接");  
		};  
		
	}  

	//发送消息
	function send(message){

		if(!socketStatus){
			toast.show({msg:'当前未连接服务器,请检查网络连接情况。'})
			return false;
		}

		if(!message){
			toast.show({msg:'参数无效或未指定参数。'})
			return false;
		}

		if(!webSocket){
			toast.show({msg:'连接异常，请退出系统后重新登录。'})
			return false;
		}

		//执行发送
		webSocket.send(message);
		return true;
		
	}
	
	function getStatus(){
		return socketStatus		;
	}
	//销毁
	function destory(){
		webSocket = null;
		socketStatus = false;
	}
	var config = {
		init: initSocket,
		send: send ,
		destory: destory ,
		getStatus: getStatus
	}
	return config;
	
})